package net.lab1024.sa.admin.module.business.yct.yctTeeth.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import net.lab1024.sa.admin.module.business.yct.yctTeeth.dao.YctTeethHospitalDao;
import net.lab1024.sa.admin.module.business.yct.yctTeeth.domain.entity.YctTeethHospitalEntity;
import net.lab1024.sa.admin.module.business.yct.yctTeeth.domain.form.YctTeethHospitalAddForm;
import net.lab1024.sa.admin.module.business.yct.yctTeeth.domain.form.YctTeethHospitalQueryForm;
import net.lab1024.sa.admin.module.business.yct.yctTeeth.domain.form.YctTeethHospitalUpdateForm;
import net.lab1024.sa.admin.module.business.yct.yctTeeth.domain.vo.WeChatAccessTokenVo;
import net.lab1024.sa.admin.module.business.yct.yctTeeth.domain.vo.YctTeethHospitalVO;
import net.lab1024.sa.admin.module.business.yct.yctTeeth.manager.YctTeethHospitalManager;
import net.lab1024.sa.admin.module.business.yct.yctproductinstructions.domain.form.YctProductInstructionsQueryForm;
import net.lab1024.sa.base.common.util.*;
import net.lab1024.sa.base.common.domain.ResponseDTO;
import net.lab1024.sa.base.common.domain.PageResult;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 易齿通口腔门诊 Service
 *
 * @Author zhangben
 * @Date 2024-11-07 09:39:15
 * @Copyright 20241107
 */

@Service
public class YctTeethHospitalService {

    @Resource
    private YctTeethHospitalDao yctTeethHospitalDao;
    @Resource
    private YctTeethHospitalManager yctTeethHospitalManager;
    @Autowired
    private RedisUtil redisUtil;
//    @Autowired
//    private CrmebUtil CrmebUtil;


    @Autowired
    private RestTemplateUtil restTemplateUtil;

    /**
     * 分页查询
     *
     * @param queryForm
     * @return
     */
    public PageResult<YctTeethHospitalVO> queryPage(YctTeethHospitalQueryForm queryForm) {
        Page<?> page = SmartPageUtil.convert2PageQuery(queryForm);
        List<YctTeethHospitalVO> list = yctTeethHospitalDao.queryPage(page, queryForm);
        PageResult<YctTeethHospitalVO> pageResult = SmartPageUtil.convert2PageResult(page, list);
        return pageResult;
    }

    /**
     * 添加
     */
    public synchronized ResponseDTO<String> add(YctTeethHospitalAddForm addForm) {

        YctTeethHospitalEntity yctTeethHospitalEntity = SmartBeanUtil.copy(addForm, YctTeethHospitalEntity.class);
//        yctTeethHospitalDao.insert(yctTeethHospitalEntity);
        return yctTeethHospitalManager.insertHospitalEntity(yctTeethHospitalEntity,addForm.getEmployeeAddForm());
    }

    /**
     * 更新
     *
     * @param updateForm
     * @return
     */
    public ResponseDTO<String> update(YctTeethHospitalUpdateForm updateForm) {
        YctTeethHospitalEntity yctTeethHospitalEntity = SmartBeanUtil.copy(updateForm, YctTeethHospitalEntity.class);
        yctTeethHospitalDao.updateById(yctTeethHospitalEntity);
        return ResponseDTO.ok();
    }


    /**
     * 单个删除
     */
    public ResponseDTO<String> delete(Long hospiatlId) {
        if (null == hospiatlId){
            return ResponseDTO.ok();
        }

        yctTeethHospitalDao.updateDeleted(hospiatlId, true);
        return ResponseDTO.ok();
    }

    public  PageResult<YctTeethHospitalVO> queryPageList(YctProductInstructionsQueryForm queryForm) {
        Page<?> page = SmartPageUtil.convert2PageQuery(queryForm);
        List<YctTeethHospitalVO> list = yctTeethHospitalDao.queryPageList(page, queryForm);
        PageResult<YctTeethHospitalVO> pageResult = SmartPageUtil.convert2PageResult(page, list);
        return pageResult;
    }

    public YctTeethHospitalVO select(Long hospiatlId) {
        YctTeethHospitalEntity instructionsEntity = yctTeethHospitalDao.selectById(hospiatlId);
        if (null == instructionsEntity) {
            return null;
        }

        YctTeethHospitalVO updateFormVO = SmartBeanUtil.copy(instructionsEntity, YctTeethHospitalVO.class);
        return updateFormVO;

    }

    public Map<String, Object> getQr(JSONObject data) {
        Map<String, Object> map = new HashMap<>();
        StringBuilder scene = new StringBuilder();
        String page = "";
        try{
            if(null != data){
                Map<Object, Object> dataMap = JSONObject.toJavaObject(data, Map.class);

                for (Map.Entry<Object, Object> m : dataMap.entrySet()) {
                    if("path".equals(m.getKey())){
                        //前端路由， 不需要拼参数
                        page = m.getValue().toString();
                        continue;
                    }
                    if (scene.length() > 0) {
                        scene.append(",");
                    }
                    scene.append(m.getKey()).append(":").append(m.getValue());
                }
            }
        }catch (Exception e){
//            throw new Exception("url参数错误 " + e.getMessage());
        }
        map.put("code", createQrCode(page, scene.length() > 0 ? scene.toString() : ""));
        return map;
    }

    public String createQrCode(String page, String scene) {
        String miniAccessToken = getMiniAccessToken();
        String url = StrUtil.format("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={}", miniAccessToken);
        HashMap<String, Object> map = new HashMap<>();
        map.put("scene", scene);
        map.put("page", page);
        map.put("width", 200);
        byte[] bytes = restTemplateUtil.postJsonDataAndReturnBuffer(url, new JSONObject(map));
        String response = new String(bytes);
        if (StringUtils.contains(response, "errcode")) {

//            logger.error("微信生成小程序码异常"+response);
            JSONObject data = JSONObject.parseObject(response);
            // 保存到微信异常表
//            wxExceptionDispose(data, "微信小程序生成小程序码异常");
            if ("40001".equals(data.getString("errcode"))) {
                redisUtil.delete("wechat_mini_accessToken");
                miniAccessToken = getMiniAccessToken();
                url = StrUtil.format("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={}", miniAccessToken);
                bytes = restTemplateUtil.postJsonDataAndReturnBuffer(url, new JSONObject(map));
                response = new String(bytes);
                if (StringUtils.contains(response, "errcode")) {
                    JSONObject data2 = JSONObject.parseObject(response);
                    // 保存到微信异常表
                    return "";
                } else {
                    try {
                        return CrmebUtil.getBase64Image(Base64.encodeBase64String(bytes));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        try {
            return CrmebUtil.getBase64Image(Base64.encodeBase64String(bytes));
        } catch (Exception e) {
            e.printStackTrace();

            System.out.println("微信小程序码转换Base64异常");
            return "";
//            throw new CrmebException("微信小程序码转换Base64异常");
        }
    }


    public String getMiniAccessToken() {
        boolean exists = redisUtil.exists("wechat_mini_accessToken");
        if (exists) {
            Object accessToken = redisUtil.get("wechat_mini_accessToken");
            return accessToken.toString();
        }
        String appId = "wxe473a31fd17b48c4";
//        if (StrUtil.isBlank(appId)) {
//            throw new CrmebException("微信小程序appId未设置");
//        }
        String secret = "3d6997955c4b1a7285aef8f729bfbc3a";
//        if (StrUtil.isBlank(secret)) {
//            throw new CrmebException("微信小程序secret未设置");
//        }
        WeChatAccessTokenVo accessTokenVo = getAccessToken(appId, secret, "mini");
        // 缓存accessToken
        redisUtil.set("wechat_mini_accessToken", accessTokenVo.getAccessToken(),
                accessTokenVo.getExpiresIn().longValue() - 1800L, TimeUnit.SECONDS);
        return accessTokenVo.getAccessToken();
    }

    private WeChatAccessTokenVo getAccessToken(String appId, String secret, String type) {
        String url = StrUtil.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={}&secret={}", appId, secret);
        JSONObject data = restTemplateUtil.getData(url);
        if (ObjectUtil.isNull(data)) {
//            throw new CrmebException("微信平台接口异常，没任何数据返回！");
        }
        if (data.containsKey("errcode") && !"0".equals(data.getString("errcode"))) {
            if (data.containsKey("errmsg")) {
                System.out.println("微信接口调用失败：" + data.getString("errcode") + data.getString("errmsg"));
                // 保存到微信异常表
//                wxExceptionDispose(data, StrUtil.format("微信获取accessToken异常，{}端", type));
//                throw new CrmebException("微信接口调用失败：" + data.getString("errcode") + data.getString("errmsg"));
            }
        }
        return JSONObject.parseObject(data.toJSONString(), WeChatAccessTokenVo.class);
    }

}
